
const errcode = require('../utils/errcode')

module.exports = async (ctx, next) => {
  const loginId = ctx.session.loginId
  const token = ctx.session.token || ctx.request.body.token || ctx.query.token

  if (loginId) {
    ctx.state.loginId = loginId
    await next()
    return
  } else if (token) {
    const [valid, userId] = await ctx.service.user.validateToken(token)

    if (valid) {
      ctx.state.loginId = userId
      await next()
      return
    }
  }

  ctx.error(errcode.AUTH_REQUIRED)
}
